<?php
/**
 * @package     CiMS.framework
 *
 * @copyright   Copyright (C) 2012 Cimaron Shanahan. All rights reserved.
 * @license     http://opensource.org/licenses/mit-license.php MIT License
 */
defined('CiMS') or die;


/**
 * CiMS Session Class
 */
class CiMSSession extends CiMSObject {

	protected $_next = NULL;
	protected $_now = NULL;

	/**
	 * Override CiMSObject::getInstance()
	 */
	public static function getInstance($data = array()) {
		return parent::getInstance($data);
	}

	/**
	 * Constructor
	 */
	public function __construct() {
		session_start();

		//Hook last single use session data in
		$this->_now = new CiMSObject((array)$_SESSION['__single']);
		$_SESSION['__single'] = array();

		//Hook next single use session data in
		$this->_next = new CiMSObject();
		$this->_next->setRef($_SESSION['__single']);

		//Hook session data in
		$this->setRef($_SESSION);
	}

	/**
	 * Get session variable
	 *
	 * @param   string   $key       Key
	 * @param   mixed    $default   Default value if not set
	 *
	 * @return  mixed
	 */
	public function get($key, $default = NULL) {

		if ($this->_now->has($key)) {
			return $this->_now->get($key);
		}

		return parent::get($key, $default);
	}

	/**
	 * Set session variable
	 *
	 * @param   string   $key     Key
	 * @param   mixed    $value   Value
	 */
	public function set($key, $value) {
		$this->_next->clear($key);
		$this->_now->clear($key);
		parent::set($key, $value);
	}

	/**
	 * Set single use session variable
	 *
	 * @param   string   $key     Key
	 * @param   mixed    $value   Value
	 */
	public function setOnce($key, $value) {
		parent::clear($key);
		$this->_next->set($key, $value);
		$this->_now->set($key, $value);
	}

	/**
	 * Session variable exists
	 *
	 * @param   string   $key   Key
	 *
	 * @return  boolean
	 */
	public function has($key) {
		return (parent::has($key) || $this->_now->has($key));
	}

	/**
	 * Clear session variable
	 *
	 * @param   string   $key   Key
	 */
	public function clear($key) {
		$this->_now->clear($key);
		$this->_next->clear($key);
		parent::clear($key);
	}

}

